package com.slipper.sfts.websocket;

import com.slipper.common.util.StringUtil;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

public class WebsocketManager {
    private static final Logger logger = LoggerFactory.getLogger(WebsocketManager.class);
    private static final ConcurrentHashMap<String, WebSocketSession> sessionPool = new ConcurrentHashMap<>();

    public static void addSession(String memberId, WebSocketSession session) {
        if (StringUtil.isBlank(memberId)) return;

        closeSession(memberId);
        sessionPool.put(memberId, session);
        logger.info("当前在线人数：{}", sessionPool.size());
    }

    public static void closeSession(String memberId) {
        if (StringUtil.isBlank(memberId) || !sessionPool.containsKey(memberId)) return;

        try {
            sessionPool.remove(memberId).close();
            logger.info("当前在线人数：{}", sessionPool.size());
        } catch (Exception e) {
            logger.error("重复登录，踢出用户关闭连接失败！", e);
        }
    }

    public static void sendMessage(String memberId, String message) {
        if (StringUtil.isBlank(memberId) || !sessionPool.containsKey(memberId)) return;

        try {
            WebSocketSession session = sessionPool.get(memberId);
            session.sendMessage(new TextMessage(message));
        } catch (Exception e) {
            logger.error("发送消息失败：{}", message, e);
        }
    }
}
